#include <iostream>
#include <sstream>
#include "privatecloud.pb.h"
#include "tcp_connection.h"
#include "utility.h"
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>

using boost::asio::ip::tcp;
using namespace std;
using namespace private_could;

class session
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        boost::bind(&session::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

private:
    void handle_init(packet& p)
    {
        repo = boost::filesystem::initial_path();
        repo /= ".repo";
        boost::filesystem::create_directory(repo);
        repo /= p.file_name();
        cout << "repo name: " << p.file_name() << endl;

        if (boost::filesystem::create_directory(repo)) {
            cout << " Repository is created @ " << repo.string() << " successfully." << endl;
            boost::filesystem::current_path(repo);
        }
    }
  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {
	  istringstream iss(std::string(data_, bytes_transferred));
	  packet p;
	  p.ParseFromIstream(&iss);

	  cout << p.command()<< endl;

	  switch(p.command())
	  {
      case packet::cmd_type::packet_cmd_type_INIT:
          handle_init(p);
        break;
      case packet::cmd_type::packet_cmd_type_BACKUP:
          switch(p.sub_command())
          {
          case packet::sub_cmd_type::packet_sub_cmd_type_CONTACT:
              {
                  cout << "There are " << p.contacts_size() << " new contacts" << endl;;
                  for (packet_contact c : p.contacts())
                  {
                      cout << "Name: " << c.name() << endl;
                      cout << "Phone: " << c.phone() << endl;
                      cout << "Email: " << c.email() << endl;
                  }
                  string current_time = get_current_time();
                  string fileName = current_time + ".ctt";
                  boost::filesystem::path p(repo);
                  p /= fileName;
                  ofstream out(p.string(), ios::binary);
                  out.write(data_, bytes_transferred);
                  out.flush();
                  out.close();
              }
            break;
          default:
            cout << "NOt support yet." << endl;
            break;
          }
        break;
      default:
        cout << "Nothing else." << endl;
	  }

      boost::asio::async_write(socket_,
          boost::asio::buffer(data_, bytes_transferred),
          boost::bind(&session::handle_write, this,
            boost::asio::placeholders::error));
    }
    else
    {
      delete this;
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {
      socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      delete this;
    }
  }
  boost::filesystem::path repo;
  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
};

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    start_accept();
  }

private:
  void start_accept()
  {
    session* new_session = new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start();
    }
    else
    {
      delete new_session;
    }

    start_accept();
  }

  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

int main(int argc, char *argv[])
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    try
    {
        if (argc != 2)
        {
          std::cerr << "Usage: async_tcp_echo_server <port>\n";
          return 1;
        }

        boost::asio::io_service io_service;

        using namespace std; // For atoi.
        server s(io_service, atoi(argv[1]));

        io_service.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    /*packet p;
    p.set_command(private_could::packet_cmd_type::packet_cmd_type_INIT);
    p.set_file_name(string("MI2S"));
    ostringstream oss;
    p.SerializeToOstream(&oss);

    string serialized = oss.str();
    cout << serialized << endl;

    packet p1;
    istringstream iss(serialized);
    p1.ParseFromIstream(&iss);

    cout << p1.file_name() << endl;
    cout << p1.reserved() << endl;*/

    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}
